var tux = {anim:null, n:0, x:180, y:142};
var bg = {anim:null, n:0, x:0, y:0};
var bg2 = {anim:null, n:0, x:"null", y:0};

window.addEventListener('load', init, false);

function init() {
	// Exemple d'utilisation du pré-chargement d'images
	images=loadImages(
	  {"bg":"images/background1.png",
	   "pikachu":"images/pikachuskate.png",
	   },
	  start); 
}

function start() {
	var canvas0 = document.getElementById('player');
	var context0 = canvas0.getContext('2d');
	tux.anim = setInterval(anime, 50);
	function anime() {
		context0.clearRect(0, 0, canvas0.width, canvas0.height);
                if(bg.x <= -2315 && bg.x > -3215)
                {
                    if(bg2.x == "null")
                    {
                        bg2.x = bg.x + 3215;
                    }
                    context0.drawImage(images["bg"], bg2.x,bg2.y);
                    bg2.x -= 16; 
                } else if(bg.x <= -3215)
                {
                    bg = bg2; bg2 = {anim:null, n:0, x:"null", y:0};
                }
		context0.drawImage(images["bg"], bg.x,bg.y);
                

                bg.x -= 16;
                context0.drawImage(images["pikachu"], tux.x,tux.y, 30, 40);
                
	}
}

function loadImages(list, loaded) {
    var nbImages = 0;
    var img = new Object();
    for (var i in list) {
        img[i] = new Image();
        nbImages++;
        img[i].onload = function () {
            nbImages--;
            if (nbImages == 0) loaded();
        };
        // exemple d'utilisation de closures - cf:
        // http://www.siteduzero.com/tutoriel-3-123380-les-closures-en-javascript.html
        var aborted = false;
        img[i].onerror = img[i].onabort = ( function(arg1) {
            return function() {
                if (!aborted) {                                 
                    aborted=true;
                    alert("couldn't load image: '"+list[arg1]+"' - aborted");
                }
            };
        } ) ( i );
        img[i].src = list[i];
    }
    return img;
}

